#include"com.hpp"

class UdpClient
{
  public:

    UdpClient(string server_ip,int server_port)
      :_sockfd(-1)
       ,_server_ip(server_ip)
       ,_server_port(server_port)
  {

  }

    bool InitClient()
    {
      _sockfd = socket(AF_INET,SOCK_DGRAM,0);
      if(_sockfd<0)
      {
        cout<<"socket fail"<<endl;
        return  false;
      }
      return true;
    }

    void Start()
    {
      string msg;
      struct sockaddr_in peer;
      memset(&peer,'\0',sizeof(peer));
      peer.sin_family=AF_INET;
      peer.sin_port = htons(_server_port);
      peer.sin_addr.s_addr= inet_addr(_server_ip.c_str());
      while(true)
      {
        cout<<"please Enter#:";
        getline(cin,msg);
        sendto(_sockfd,msg.c_str(),msg.size(),0,(struct sockaddr*)&peer,sizeof(peer));
#define SIZE 128
        char buffer[SIZE];
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        ssize_t size = recvfrom(_sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&tmp, &len);
        if (size > 0){
          buffer[size] = '\0';
          std::cout << buffer << std::endl;
        }   
      }

    }

    ~UdpClient()
    {
      if(_sockfd>=0)
      {
        close(_sockfd);
      }
    }
  private:
    int _sockfd;
    int _server_port;
    string _server_ip;
};

int main(int argc,char* argv[])
{
  if(argc!=3)
  {
    cout<<"Usage: "<<argv[0]<<"server_ip server_port"<<endl;
    return 1;
  }

  string server_ip = argv[1];
  int server_port = atoi(argv[2]);

  UdpClient* clt = new UdpClient(server_ip,server_port);
  clt->InitClient();
  clt->Start();
  return 0;
}

